package com.luck.easyfoodbatch.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.PointsAdapter;
import com.luck.easyfoodbatch.dialog.CustomDialog;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.mine.DaySignModel;
import com.luck.easyfoodbatch.mvp.mine.DaySignPresenter;
import com.luck.easyfoodbatch.mvp.mine.DaySignView;
import com.luck.easyfoodbatch.mvp.mine.MemberInfoModel;
import com.luck.easyfoodbatch.mvp.mine.MemberInfoPresenter;
import com.luck.easyfoodbatch.mvp.mine.MemberInfoView;
import com.luck.easyfoodbatch.mvp.mine.PointLogModel;
import com.luck.easyfoodbatch.mvp.mine.PointLogPresenter;
import com.luck.easyfoodbatch.mvp.mine.PointLogView;
import com.luck.easyfoodbatch.mvp.model.PointsModel;
import com.luck.easyfoodbatch.mvp.model.SignModel;
import com.luck.easyfoodbatch.mvp.model.UserModel;
import com.luck.easyfoodbatch.util.FileUtils;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.util.Utils;
import com.luck.easyrecyclerview.EasyRecyclerView;
import com.luck.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.luck.easyrecyclerview.decoration.RecycleViewDivider;
import com.mob.tools.utils.UIHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

public class MyPointsActivity extends BaseActivity implements DaySignView, MemberInfoView, SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnLoadMoreListener, PointLogView, PlatformActionListener, Handler.Callback {

    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    //    @BindView(R.id.btn_exchange)
//    Button btnExchange;
//    @BindView(R.id.btn_recharge)
//    Button btnRecharge;
    TextView tv_sign;
    TextView tv_share;
    TextView tv_exchange;
    TextView tv_recharge;
    private PointsAdapter adapter;
    private List<PointsModel.DataBean.ModelsBean> list = new ArrayList<>();
    private User user;
    private PointLogModel pointLogModel;
    private int totalPage = 1;
    private int page = 1;
    private int isRefresh = 0;// 0普通请求，1下拉刷新，2上拉加载
    private TextView tv_point;
    private DaySignModel daySignModel;
    private String share_title = "易食批", share_text = "这么专业的食品批发平台，好伙伴必须通知你！快来下载易食批app吧！钱赚更多也就是动动手指的事儿！", share_url = "";
    private static final int MSG_ACTION_CCALLBACK = 2;
    private MemberInfoModel memberInfoModel;
    private Intent intent = new Intent();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_points, "我的积分", "积分规则", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5F), getResources().getColor(R.color.line_color)));
        recyclerView.setLayoutManager(manager);
        adapter = new PointsAdapter(mContext);
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore);
        adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {
                View pageView = LayoutInflater.from(mContext).inflate(R.layout.my_points_head, null);
                tv_exchange = (TextView) pageView.findViewById(R.id.tv_exchange);
                tv_recharge = (TextView) pageView.findViewById(R.id.tv_recharge);
                tv_point = (TextView) pageView.findViewById(R.id.tv_point);
                tv_share = (TextView) pageView.findViewById(R.id.tv_share);
                tv_sign = (TextView) pageView.findViewById(R.id.tv_sign);

                if (user != null && !Tools.isNull(user.getAuthToken())) {
                    tv_point.setText(user.getPoint() + "");
                }
                tv_share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showShareDialog();
                    }
                });
                tv_sign.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showProgressDialog("正在签到，请稍候……");
                        daySignModel = new DaySignPresenter(MyPointsActivity.this, mContext);
                        daySignModel.daySign();
                    }
                });
                tv_exchange.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startAct(ExchangeActivity.class);
                    }
                });
                tv_recharge.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        intent.setClass(mContext, IntegralRechargeActivity.class);
                        startActivityForResult(intent, 200);
                    }
                });
                return pageView;
            }

            @Override
            public void onBindView(View headerView) {

            }
        });
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {

            }
        });
        adapter.setError(R.layout.view_error).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.resumeMore();
            }
        });
        showProgressDialog(getString(R.string.app_loading));
        pointLogModel = new PointLogPresenter(this, mContext);
        pointLogModel.getPointLogList(isRefresh, page);

        adapter.addAll(list);
        recyclerView.setAdapter(adapter);
        recyclerView.setRefreshListener(this);
    }

    @Override
    public void rightClick() {
        super.rightClick();
        startAct(IntegralDescriptionActivity.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        if (user != null) {
            share_url = "http://yishipi.com.cn/yspShare/share.html?uid=" + user.getUid();
            if (tv_point != null) {
                tv_point.setText(user.getPoint() + "");
            }
        }
    }

//    @OnClick({R.id.btn_exchange, R.id.btn_recharge})
//    public void onClick(View view) {
////        Intent intent = new Intent();
////        Bundle bundle = new Bundle();
//        switch (view.getId()) {
//            case R.id.btn_exchange:
//                startAct(ExchangeActivity.class);
//                break;
//            case R.id.btn_recharge:
//                intent.setClass(mContext, IntegralRechargeActivity.class);
//                startActivityForResult(intent, 200);
//                break;
//        }
//    }

    @Override
    public void onLoadMore() {
        //刷新
        isRefresh = 1;
        page++;
        if (!isNetworkConnected()) {
            adapter.pauseMore();
            return;
        }
        if (page > totalPage) {
            adapter.stopMore();
            return;
        }
        pointLogModel.getPointLogList(isRefresh, page);
    }

    @Override
    public void onRefresh() {
        isRefresh = 0;
        page = 1;
        pointLogModel.getPointLogList(isRefresh, page);
    }

    @Override
    public void pointLogSuccess(PointsModel model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            totalPage = model.getData().getTotalPage();
            // 下拉刷新 清空集合
            switch (isRefresh) {
                case 0:
                    list.clear();
                    list = model.getData().getModels();
                    break;
                case 1:
                    // 下拉刷新
                    list.addAll(model.getData().getModels());
                    break;
            }
            adapter.clear();
            adapter.addAll(list);
            adapter.notifyDataSetChanged();
        } else {
            T.showToast(mContext, model.getMsg());
        }
    }

    @Override
    public void daySignSuccess(SignModel signModel) {
        if (signModel.getStatus() == HttpUtil.RESULT_OK) {
            SignModel.DataBean item = signModel.getData();
            String data = item.getTotal_point();
            if (!Tools.isNull(data)) {
                // 更新积分
                if (user != null) {
                    if (!Tools.isNull(data)) {
                        user.setPoint(Integer.parseInt(data));
                    }
                    App.getInstance().saveObject(user, HttpUtil.USER_KEY);
                }
            }
            showSignDialog(1, signModel.getMsg());
        } else {
            if (!Tools.isNull(signModel.getMsg()) && signModel.getMsg().equals("今天已经签过了")) {
                showSignDialog(0, signModel.getMsg());
            } else {
                T.showToast(mContext, signModel.getMsg());
            }
        }
    }

    /**
     * 签到
     */
    private void showSignDialog(int type, String msg) {
        final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth * 3 / 4,
                App.screenHeight / 4, R.layout.wind_sign_dialog_xml, R.style.Theme_dialog);
        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
        TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
        switch (type) {
            case 0:
                tv_title.setText(msg);
                tv_content.setText("明天请记得保持哦");
                break;
            case 1:
                tv_title.setText("签到成功！");
                tv_content.setText(msg);
                break;
        }

        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                dialog.dismiss();
            }
        });
        dialog.show();
    }


    @Override
    public void memberInfoSuccess(UserModel userModel) {
        if (userModel != null && userModel.getStatus() == HttpUtil.RESULT_OK) {
            User data = userModel.getData();
            data.setAuthToken(userModel.getAuthToken());
            App.getInstance().saveObject(data, HttpUtil.USER_KEY);
            user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
            if (user != null) {
                if (tv_point != null) {
                    tv_point.setText(user.getPoint() + "");
                }
            }
        }
    }

    @Override
    public void httpStatusError() {
        T.showToast(mContext, getResources().getString(R.string.app_http_error));
    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }


    /**
     * 分享
     */
    private void showShareDialog() {
        final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth,
                App.screenHeight, R.layout.wind_share_dialog, R.style.Theme_dialog);
        ImageView iv_close = (ImageView) dialog.findViewById(R.id.iv_close);
        TextView tv_invite_code = (TextView) dialog.findViewById(R.id.tv_invite_code);
        ImageView iv_share_wechat = (ImageView) dialog.findViewById(R.id.iv_share_wechat);
        ImageView iv_share_pyq = (ImageView) dialog.findViewById(R.id.iv_share_pyq);
        ImageView iv_share_qq = (ImageView) dialog.findViewById(R.id.iv_share_qq);
        tv_invite_code.setText("邀请码：" + user.getInvite_code());
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        iv_share_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                T.showToast(mContext, "正在启动微信，请稍候...");
                wechat();
                dialog.dismiss();
            }
        });
        iv_share_pyq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                T.showToast(mContext, "正在启动微信，请稍候...");
                wechatmoments();
                dialog.dismiss();
            }
        });
        iv_share_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                T.showToast(mContext, "正在启动QQ，请稍候...");
                qq();
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 分享微信
     */
    private void wechat() {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(share_title);
        sp.setText(share_text);
        sp.setImagePath(FileUtils.IMAGE_PATH + "logo.png");
        sp.setShareType(Platform.SHARE_TEXT);
        sp.setShareType(Platform.SHARE_WEBPAGE);
        sp.setUrl(share_url);
        Platform qq = ShareSDK.getPlatform(Wechat.NAME);
        qq.setPlatformActionListener(this);
        qq.share(sp);
    }

    /**
     * 分享微信朋友圈
     */
    private void wechatmoments() {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(share_title);
        sp.setText(share_text);
        sp.setUrl(share_url);
        sp.setImagePath(FileUtils.IMAGE_PATH + "logo.png");
        sp.setShareType(Platform.SHARE_TEXT);
        sp.setShareType(Platform.SHARE_WEBPAGE);
        Platform qq = ShareSDK.getPlatform(WechatMoments.NAME);
        qq.setPlatformActionListener(this);
        qq.share(sp);
    }

    /**
     * 分享QQ
     */
    private void qq() {
        Platform.ShareParams shareParams = new Platform.ShareParams();
        shareParams.setTitle(share_title);
        shareParams.setTitleUrl(share_url); // 标题的超链接
        shareParams.setText(share_text);
        shareParams.setComment("我对此分享内容的评论");
        shareParams.setSite(getString(R.string.app_name));
        shareParams.setImagePath(FileUtils.IMAGE_PATH + "logo.png");
        shareParams.setSiteUrl(share_url);
        Platform qq = ShareSDK.getPlatform(mContext, QQ.NAME);
        qq.setPlatformActionListener(this);
        qq.share(shareParams);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.arg1) {
            case 1: {
                // 成功
                T.showToast(mContext, "分享成功");
            }
            break;
            case 2: {
                // 失败
                T.showToast(mContext, "分享失败");
            }
            break;
            case 3: {
                // 取消
                T.showToast(mContext, "分享取消");
            }
            break;
        }
        return false;
    }

    @Override
    public void onCancel(Platform platform, int action) {
        // 取消
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 3;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onComplete(Platform platform, int action,
                           HashMap<String, Object> arg2) {
        // 成功
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);

    }

    @Override
    public void onError(Platform platform, int action, Throwable t) {
        // 失敗
        // 打印错误信息,print the error msg
        t.printStackTrace();
        // 错误监听,handle the error msg
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 2;
        msg.arg2 = action;
        msg.obj = t;
        UIHandler.sendMessage(msg, this);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    // 刷新我的积分
                    memberInfoModel = new MemberInfoPresenter(this, mContext);
                    memberInfoModel.getMemberInfo();
                    break;
            }
        }
    }
}
